<!-- 多个版本累计了很多判断条件，导致代码很臃肿，需要慢慢看 -->
<template>
  <page-wrap ref="pageWrap" hideTab back title="职途报告" :showTop="false" :dark="loaded ? false : true"
    :hideSafeArea="true">
    <view class="create-report" :style="'padding-top:' + navHeight + 'px;'">
      <careerReportJobTips ref="careerReportJobTips" @update:isFill="updateIsFill" @update:status="updateStatus" />
      <view class="tips" v-if="showDeliverBtn">
        <span>手动更新最终版的在线报告后，才可确认邮寄实体报告</span>
      </view>
      <view class="img-box">
        <scroll-view scroll-y class="scroll-view" v-if="reportImgs.length">
          <view class="tip">可点击查看图片</view>
          <view class="box" v-for="(item, index) in reportImgs" :key="index">
            <image class="img-w" mode="widthFix" :src="item" @click="previewImg(item)"></image>
          </view>
        </scroll-view>
        <view class="sample" v-if="!reportImgs.length">
          <image :src="sampleImg" class="sample-img"></image>
          <view class="sample-text">{{ sampleText }}</view>
        </view>
        <view :class="['operate-bar', isIOS ? 'iosPd' : 'androidPd']">
          <view v-if="fromSxh == 'sxh'" class="success">
            <!-- 如果来自统一的二维码解析页面，就要显示去求职工具首页按钮 -->
            <u-button class="btn" type="primary" shape="circle" @click="handleReturnSxh">去求职工具首页</u-button>
          </view>
          <view v-else-if="fromSxh == 'fromSxhQrCode'" class="success">
            <!-- 填写求职意向并且匹配到了岗位 -->
            <template v-if="status==2">
              <u-button class="medium-btn" type="primary" :plain="isFill ? true : false" shape="circle"
                @click="handleReturn">{{isFill ? '去求职工具首页' : '使用求职工具完善报告'}}</u-button>
              <u-button :class="['smaller-btn']" type="primary" shape="circle" :loading="createLoading" plain
                :plain="!isFill ? true : false"
                @click="reCreateReportFn">{{ createLoading ? '正在更新中...' : '更新职途报告' }}</u-button>
            </template>
            <!-- 默认情况 -->
            <template v-else>
              <u-button class="small-btn" style="margin-right: 14rpx" type="primary" plain shape="circle"
                @click="handleReturn">去求职工具首页</u-button>
              <u-button :class="['small-btn']" type="primary" shape="circle" :loading="createLoading"
                @click="reCreateReportFn">{{ createLoading ? '正在更新中...' : '生成职途报告' }}</u-button>
            </template>
          </view>
          <template v-else>
            <view v-if="hasReport" :class="['success', showDeliverBtn ? 'between' : 'center']">
              <!-- 具有邮递信息的情况 -->
              <template v-if="showDeliverBtn">
                <u-button class="small-btn" style="margin-right: 14rpx" type="primary" plain shape="circle"
                  @click="handleShowDeliverReport">{{
                    deliverStatus != 10
                      ? '已确定邮寄实体报告'
                      : '确定并邮寄实体报告'
                  }}</u-button>
                <u-button :class="['small-btn']" type="primary" shape="circle" :loading="createLoading"
                  @click="reCreateReportFn">{{
                    createLoading ? '正在更新中...' : '生成职途报告'
                  }}</u-button>
              </template>
              <template v-else>
                <u-button :class="['big-btn']" type="primary" shape="circle" :loading="createLoading"
                  @click="reCreateReportFn">{{
                    createLoading ? '正在更新中...' : '生成职途报告'
                  }}</u-button>
              </template>
            </view>
            <view v-else class="success center">
              <u-button :class="['big-btn']" type="primary" shape="circle" :loading="createLoading"
                @click="createReportFn">{{
                  createLoading ? '正在更新中...' : '生成在线职途报告'
                }}</u-button>
            </view>
          </template>
        </view>
      </view>
      <view class="toast fade-in" v-if="showSuccessToast">
        <img :src="createSuccessImg" class="toast-img" />
        <text>更新成功</text>
      </view>
    </view>
    <u-popup v-model="showPopup" mode="bottom" height="auto" border-radius="28" closeable>
      <view class="popup-content">
        <view class="title">
          {{
            deliverStatus == 10 ? '确认并邮寄实体职途报告' : '实体报告邮寄信息'
          }}
        </view>
        <!-- <view class="order-info" v-if="deliverDate">
          <view class="order-title">确认邮寄时间</view>
          <view class="order-num">{{ deliverDate || "-" }}</view>
        </view> -->
        <scroll-view style="height: 1100rpx" scroll-y="true">
          <view class="order-info">
            <view class="order-title">订单编号</view>
            <view class="order-num">{{
              deliverInfo.orderNo || '暂无订单信息'
            }}</view>
          </view>
          <view class="order-info">
            <view class="order-title">邮寄地址</view>
            <u-input type="textarea" v-if="deliverStatus == 10" placeholder="必填（x省x市x区x街x栋）"
              v-model="orderInfoJson.receiveAddress" />
            <view v-else class="order-num">{{
              orderInfoJson.receiveAddress || '暂无订单信息'
            }}</view>
          </view>
          <view class="order-info">
            <view class="order-title">收件手机号码</view>
            <u-input type="textarea" v-if="deliverStatus == 10" placeholder="必填" v-model="orderInfoJson.personPhone"
              maxlength="11" @blur="checkPhone" />
            <view v-else class="order-num">{{
              orderInfoJson.personPhone || '暂无订单信息'
            }}</view>
          </view>
          <view class="order-info" v-if="deliverStatus != 10">
            <view class="order-title">快递编号
              <view class="deliver-company" v-if="orderInfoJson.deliveryCompany">{{ orderInfoJson.deliveryCompany }}
              </view>
            </view>
            <!-- <input v-if="deliverStatus != 20" class="order-num" v-model="orderInfoJson.deliveryNo" /> -->
            <view :class="orderInfoJson.deliveryNo ? 'order-num' : 'order-num-grey'">{{
                orderInfoJson.deliveryNo ||
                '店小二还未发货，请等待快递编号更新~'
              }}</view>
          </view>
          <view class="order-info" v-if="deliverStatus != 10">
            <view class="order-title">发货时间</view>
            <!-- <input v-if="deliverStatus != 20" class="order-num" v-model="orderInfoJson.mailItem" /> -->
            <view :class="deliverDate ? 'order-num' : 'order-num-grey'">{{
              deliverDate || '店小二还未发货，请等待发货时间更新~'
            }}</view>
          </view>
          <view class="order-tips">
            <view class="order-tips-title">邮寄须知</view>
            <p class="tip">
              1.邮寄地址为服务下单平台（如：一览职业小程序、抖音）上的实际地址
            </p>
            <p class="tip">
              2.一经邮寄，重新生成职途报告不会同步到实体职途报告中
            </p>
            <p class="tip">3.如果其他问题，请咨询下单平台店铺客服</p>
          </view>
        </scroll-view>
        <view :class="['footer', isIOS ? 'iosPd' : 'androidPd']">
          <u-button class="footer-btn" type="primary" shape="circle"
            :disabled="deliverStatus == 20 || !deliverInfo.orderNo" :loading="deliverLoading"
            @click="personConfirmDeliverStatusFn" v-if="deliverStatus == 10">确认邮寄实体报告</u-button>
        </view>
      </view>
    </u-popup>
    <u-modal v-model="showGoBackTipVisible" :content="tipContent" @confirm="handleConfirm"></u-modal>
  </page-wrap>
</template>

<script>
import {
  getReportImage,
  createZTReportV2,
  getZtReportV2,
  rightsTree,
  getPersonRedeemInfo,
  personConfirmDeliverStatus,
} from "@/api/modules/career";
import { env } from "@/api/root";
import careerReportJobTips from "./careerReportJobTips.vue";
export default {
  components: {
    careerReportJobTips,
  },
  data() {
    return {
      navHeight: getApp().globalData.navHeight,
      sampleImg: this.$imgBase + "careerPath/sampleImg.png",
      createSuccessImg: this.$imgBase + "report/createSuccessImg.png",
      sampleText: "示例",
      createBtnText: "生成在线职途报告",
      tipContent: "您当前还没完成任意一项权益，无法生成职途报告",
      createStatus: 0,
      deliverLoading: false,
      showSuccessToast: false,
      showSuccessCount: 0,
      deliverStatus: 0,
      deliverDate: "",
      showPopup: false,
      reportImgs: [],
      deliverInfo: "",
      cardType: "",
      showGoBackTip: false,
      showGoBackTipVisible: false,
      reportGenerated: false,
      hasReport: false,
      createLoading: false,
      showDeliverBtn: false,
      retryCount: 0,
      MAX_RETRY_TIMES: 20,
      timer: null,
      personId: "",
      cardType: "",
      isIOS: uni.getSystemInfoSync().platform == "ios",
      orderInfoJson: {
        orderNo: "",
        receiveAddress: "",
        personPhone: "",
        deliveryNo: "",
        mailItem: "",
      },
      fromSxh: "",
      isFill: false,
      status: 0, //careerReportJobTips里的status
    };
  },
  onHide() {
    this.endRequest();
  },
  onLoad(opt) {
    this.fromSxh = opt.fromSxh;
    // 如果是来自双选会，则获取假的personId;
    if (this.fromSxh == "sxh") {
      this.personId = uni.getStorageSync("SxhPersonId");
    } else {
      this.personId = uni.getStorageSync("person-id").slice(2);
    }
    this.cardType = uni.getStorageSync("cardType");

    if (env === "dev" || env === "prod") {
      this.MAX_RETRY_TIMES = 10;
    }
    if (env === "test") {
      this.MAX_RETRY_TIMES = 20;
    }
  },
  onUnload() {
    this.endRequest();
  },
  onShow() {
    // this.rightsTreeFn();
    this.getReportImageFn();
    this.getPersonRedeemInfoFn();
    this.$refs.careerReportJobTips.getJobList();
    // 如果求职意向更新了，则生成职途报告
    const aimUpdated = uni.getStorageSync("aimUpdated");
    if (aimUpdated) {
      this.createReportFn();
      uni.removeStorageSync("aimUpdated");
    }
  },
  beforeDestroy() {},
  methods: {
    updateStatus(status) {
      this.status = status;
    },
    updateIsFill(isFill) {
      this.isFill = isFill;
    },
    handleConfirm() {
      this.handleReturn();
    },
    handleReturnSxh() {
      uni.reLaunch({ url: "/pagesSub/doubleChannelChoosingMeeting/index" });
    },
    handleReturn() {
      uni.navigateTo({ url: "/pagesSub/userCenter/careerPathV2/index" });
    },
    previewImg(src) {
      uni.previewImage({
        urls: [src],
      });
    },
    checkPhone() {
      const phone = this.orderInfoJson.personPhone;
      const regex = /^1[3-9]\d{9}$/;
      if (!regex.test(phone)) {
        uni.showToast({
          title: "请输入正确手机号",
          icon: "none",
          duration: 2000,
        });
      } else {
        console.log("手机号正常");
      }
    },
    async rightsTreeFn() {
      const res = await rightsTree({ uid: "" });
      if (res.code == 200) {
        const temp = this.findElement(res.data);
        this.showGoBackTip = temp ? false : true;
        if (this.showGoBackTip && this.fromSxh == "fromSxhQrCode") {
          this.tipContent = "您当前还没完成任意一项权益，无法生成职途报告";
          this.showGoBackTipVisible = true;
        }
      }
    },
    findElement(arr) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].children.length) {
          for (let j = 0; j < arr[i].children.length; j++) {
            if (arr[i].children[j].rightStatus == 2) {
              return true;
            }
          }
        }
      }
    },
    personConfirmDeliverStatusFn() {
      if (this.deliverStatus == 20 || this.deliverStatus == 30) {
        // this.showPopup = false;
        return;
      }
      this.deliverLoading = true;
      console.log("this.orderInfoJson", this.orderInfoJson);
      const params = {
        personId: this.personId,
        deliverStatus: 20,
        orderNo: this.deliverInfo.orderNo,
        orderInfoJson: {
          personPhone: this.orderInfoJson.personPhone,
          receiveAddress: this.orderInfoJson.receiveAddress,
        },
      };
      if (this.orderInfoJson.personPhone && this.orderInfoJson.receiveAddress) {
        personConfirmDeliverStatus(params)
          .then((res) => {
            if (res.code == 200) {
              this.deliverStatus = res.data.deliverStatus;
              this.getPersonRedeemInfoFn();
            }
          })
          .finally(() => {
            this.deliverLoading = false;
            // this.showPopup = false;
          });
      } else {
        this.deliverLoading = false;
        uni.showToast({
          title: "手机号和地址不可为空",
          icon: "none",
          duration: 2000,
        });
      }
    },
    getPersonRedeemInfoFn() {
      const params = {
        personId: this.personId,
        cardType: this.cardType,
      };
      getPersonRedeemInfo(params).then((res) => {
        if (res.code == 200) {
          if (res.data.orderNo) {
            this.showDeliverBtn = true;
            this.deliverInfo = res.data;
            this.deliverDate = res.data.deliverDate ? res.data.deliverDate : "";
            this.deliverStatus = res.data.deliverStatus
              ? res.data.deliverStatus
              : 0;
          } else {
            this.showDeliverBtn = false;
          }
          if (res.data.orderInfoJson) {
            this.orderInfoJson = res.data.orderInfoJson;
          }
        }
      });
    },
    handleShowDeliverReport() {
      this.showPopup = true;
    },
    handleShowSuccessToast() {
      const showSuccessCount = uni.getStorageSync("showSuccessCount");
      if (showSuccessCount == 0) {
        uni.setStorageSync("showSuccessCount", 1);
        this.showSuccessToast = true;
        setTimeout(() => {
          this.showSuccessToast = false;
        }, 2000);
      }
    },
    handleSubscribe() {
      uni.requestSubscribeMessage({
        tmplIds: ["aRgtnpYL5P6fXRO53Zw5nU7TRm0Q--p1iq8BtQhU1xs"],
        complete: (res) => {
          Object.keys(res).forEach((key) => {
            if (res[key] === "accept") {
              console.log("用户进行了订阅消息通知");
            }
          });
        },
      });
    },
    async getReportImageFn() {
      let personId;
      if (this.fromSxh == "sxh") {
        // 如果是来自双选会，则获取假的personId;
        personId = env == "test" ? 19588814 : "24885304"; // TODO:
      } else {
        personId = +this.personId;
      }
      const params = {
        ylPositionId: personId,
        templateCode: "zt_report",
      };
      const res = await getReportImage(params);
      if (res.code == 200 && Array.isArray(res.data) && res.data.length) {
        this.hasReport = true;
        this.handleShowSuccessToast();
        let imgList = [];
        res.data.forEach((item) => {
          imgList.push(item.oneFileImg);
        });
        this.reportImgs = imgList;
      }
    },
    reCreateReportFn() {
      this.retryCount = 0;
      this.createReportFn();
    },
    async createReportFn() {
      if (this.fromSxh == "fromSxhQrCode") {
        this.handleSubscribe();
      }
      if (this.showGoBackTip) {
        this.showGoBackTipVisible = true;
        return;
      }
      this.createLoading = true;
      this.createBtnText = "在线职途报告生成中";
      this.sampleText = "在线职途报告拼命生成中~";
      const params = {
        cardType: this.cardType,
        personId: this.personId,
        openId: uni.getStorageSync("openid"),
      };
      const res = await createZTReportV2(params);
      if (res.code == 200) {
        setTimeout(() => {
          this.startRequest();
        }, 10000);
      } else {
        this.createLoading = false;
        uni.showToast({
          title: res.status_desc,
          icon: "none",
          duration: 1500,
        });
      }
    },
    startRequest() {
      this.timer = setInterval(() => {
        if (this.retryCount < this.MAX_RETRY_TIMES) {
          this.getZtReportStatus();
        } else {
          clearInterval(this.timer);
        }
      }, 10000);
    },
    endRequest() {
      clearInterval(this.timer);
      this.createLoading = false;
      this.timer = null;
    },
    // 获取当前职途报告的生成状态
    async getZtReportStatus() {
      try {
        const res = await getZtReportV2({
          personId: this.personId,
        });
        if (res.code === 200 && res.data.stateV2 !== undefined) {
          const stateV2 = res.data.stateV2;
          if (stateV2 === 1) {
            this.reportGenerated = true; // 报告已生成，停止循环请求

            this.createBtnText = "生成在线职途报告";
            this.sampleText = "示例";

            this.showSuccessToast = true;
            setTimeout(() => {
              this.showSuccessToast = false;
            }, 2000);
            this.retryCount = 0;
            this.endRequest();
            this.getReportImageFn();
          } else if (stateV2 === 0) {
            uni.showToast({
              title: "职途报告正在生成中~",
              icon: "none",
              duration: 1500,
            });
          } else if (stateV2 === 2) {
            this.retryCount = 0;
            this.createBtnText = "生成在线职途报告";
            this.sampleText = "示例";
            this.endRequest();
            uni.showToast({
              title: "职途报告生成失败，请重新点击生成报告按钮",
              icon: "none",
              duration: 1500,
            });
            this.reportGenerated = true; // 虽然报告未成功生成，但也要停止循环请求
          }
        } else if (res.code === 201) {
          this.retryCount = 0;
          this.createBtnText = "生成在线职途报告";
          this.sampleText = "示例";
          this.endRequest();
          uni.showToast({
            title: "请先完成一项测评或完善简历",
            icon: "none",
            duration: 1500,
          });
        } else {
          this.retryCount = 0;
          this.createBtnText = "生成在线职途报告";
          this.sampleText = "示例";
          this.endRequest();
          uni.showToast({
            title: res.status_desc,
            icon: "none",
            duration: 1500,
          });
        }
      } catch (err) {
        this.retryCount = 0;
        this.createBtnText = "生成在线职途报告";
        this.sampleText = "示例";
        this.endRequest();
        uni.showToast({
          title: err.message,
          icon: "none",
          duration: 1500,
        });
      }

      // 每次尝试后增加重试计数
      this.retryCount++;

      // 如果超过最大重试次数且报告仍未生成
      if (!this.reportGenerated && this.retryCount >= this.MAX_RETRY_TIMES) {
        uni.showToast({
          title: "超过最大重试次数，职途报告仍在生成中，请稍后重新进来此页面",
          icon: "none",
          duration: 1500,
        });
        this.createLoading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
$img-base-person: $img-base + "careerPath/";

.create-report {
  width: 100%;
  height: 90vh;
  background-image: url($img-base + "careerPath/consultantHallBg.png?v=2");
  background-size: 100% auto;
  background-repeat: no-repeat;
  background-color: #fff5ea;
  display: flex;
  flex-direction: column;

  .tips {
    width: 100%;
    height: 72rpx;
    font-size: 28rpx;
    background-color: #fff3eb;
    color: #ff670f;
    padding: 14rpx 26rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    justify-content: center;
  }

  .img-box {
    border-radius: 16rpx;
    overflow: hidden;
    margin: 24rpx 24rpx 0 24rpx;

    .tip {
      text-align: center;
      color: #555;
    }

    .scroll-view {
      height: calc(100vh - 384rpx);
      flex-grow: 1;
      .box {
        margin-top: 12rpx;
        box-shadow: 0 4px 8px rgba(134, 132, 132, 0.2);
      }
      .box:last-child {
        padding-bottom: calc(constant(safe-area-inset-bottom));
        padding-bottom: calc(env(safe-area-inset-bottom));
      }

      .img-w {
        width: 100%;
      }
    }
  }

  .sample {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    .sample-img {
      width: 706rpx;
      height: 928rpx;
      margin: 88rpx 44rpx 0 0;
    }

    .sample-text {
      font-size: 32rpx;
      padding: 6rpx 32rpx;
      color: #333;
      background: #e5e5e5;
      border-radius: 8rpx;
    }
  }

  .operate-bar {
    display: flex;
    justify-content: space-around;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 99;

    .save-btn {
      flex-shrink: 0;
      width: 90%;
    }

    .success {
      display: flex;
      justify-content: space-between;
      padding: 0 32rpx;
      width: calc(100%);
      .mr14 {
        margin-right: 14rpx;
      }
      .smaller-btn {
        width: 38.87%;
      }
      .small-btn {
        width: 48%;
      }

      .medium-btn {
        width: 58.2%;
      }
      .big-btn {
        width: 92%;
      }
      .btn {
        width: 100%;
      }
    }

    .between {
      justify-content: space-between;
    }

    .center {
      justify-content: center;
    }

    ::v-deep .u-btn--primary--plain {
      background-color: #fff4ef !important;
      color: #777777;
    }
  }

  .toast {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    z-index: 99;
    width: 400rpx;
    height: 400rpx;
    background: rgba(0, 0, 0, 0.6);
    box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(151, 151, 151, 0.5);
    border-radius: 28rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    color: #fff;
    font-size: 40rpx;

    .toast-img {
      width: 220rpx;
      height: 220rpx;
      margin-top: 20rpx;
    }
  }

  @keyframes fadeIn {
    from {
      width: 0;
      height: 0;
      opacity: 0;
    }

    to {
      width: 400rpx;
      height: 400rpx;
      opacity: 1;
    }
  }

  .fade-in {
    animation: fadeIn 0.3s ease-in;
  }
}

::v-deep .u-drawer__scroll-view {
  background-color: #f4f6f8 !important;
}

::v-deep .u-close--top-right {
  padding: 20rpx;
}

.popup-content {
  .title {
    font-weight: 600;
    font-size: 36rpx;
    color: #222222;
    padding: 48rpx 0 30rpx 24rpx;
  }

  .order-info {
    background: #ffffff;
    border-radius: 16rpx;
    margin: 16rpx;
    padding: 24rpx;

    ::v-deep .u-input__textarea {
      min-height: 40rpx !important;
      color: #777777;
    }

    .order-title {
      font-weight: 600;
      font-size: 32rpx;
      color: #222222;
      margin-bottom: 22rpx;
      display: flex;
      flex-direction: row;
      align-items: center;

      .deliver-company {
        /* width: 116rpx; */
        height: 32rpx;
        background: #fff3f1;
        border-radius: 16rpx;
        border: 2rpx solid #f75a3e;
        font-weight: 400;
        font-size: 22rpx;
        color: #f75a3e;
        line-height: 36rpx;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        margin-left: 8rpx;
        padding: 0 10rpx;
      }
    }

    .order-num {
      font-size: 32rpx;
      color: #777777;
    }

    .order-num-grey {
      font-size: 32rpx;
      color: #bfbfbf;
    }
  }

  .order-tips {
    padding: 36rpx 24rpx;
    background: #ffffff;
    border-radius: 16rpx;
    margin: 0 16rpx 24rpx 16rpx;

    .order-tips-title {
      font-weight: 600;
      font-size: 32rpx;
      color: #333333;
      margin-bottom: 14rpx;
    }

    .tip {
      font-size: 28rpx;
      color: #777777;
      padding: 12rpx 0;
    }
  }

  .footer {
    display: flex;
    justify-content: center;
    margin-top: 36rpx;

    .footer-btn {
      width: 90%;
    }

    ::v-deep .u-btn--primary--disabled {
      /* color: #222 !important;
      border-color: #dedede !important;
      background-color: #dedede !important; */
      color: #ffffff !important;
      border-color: #f75a3e !important;
      background-color: #f75a3e !important;
    }
  }
}

.iosPd {
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.androidPd {
  padding-bottom: calc(40rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
}
</style>
